package com.akujin.onemanga;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class OMservice extends Service {

	private static mainMenu MAIN_ACTIVITY;
	private static animelist ANIMELIST_ACTIVITY;
	private static final long UPDATE_INTERVAL = 5000;

	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	// environmental variables
	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	public static String url = "http://www.onemanga.com/";
	private static String list = "http://om-content.onemanga.com/content-data.js";
	private static String recent = url + "recent/";
	private static String popular = url + "directory/pop/";
	
	
	public static String currentManga = null;
	public static String currentPage = null;
	public static String currentChapter = null;
	public static String currentPageURL = null;
	
	public static Map animeList = null;
	public static Map popularList = null;
	public static Map recentList = null;
	public static Map chaptersList = null;
	public static Map pageList = null;

	private static HTTPHelp http = new HTTPHelp();
	
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public static void setMainActivity(mainMenu mainMenu) {
		  MAIN_ACTIVITY = mainMenu;
	}
	
	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	// service data miner
	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	
	/*	bool	refreshPopularList
	 * 
	 */
	public static boolean refreshPopularList() {
		String temp = null;
		popularList = new LinkedHashMap();
		
		if(http.getPage(popular,url,true,true)) {
			temp = http.returnResult();
			
			if(temp == null) {
				Log.v("Output", "No Result returned. Exiting.");
				return false;
			}
			else { //Success, time to parse the list
				String regex = "<td class=\"ch-subject\"><a href=\"(.+)\" >(.+)</a> <span>\\((.+)\\)</span>";
				
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(temp);
				
				int i = 0;
			    while(m.find()) {
			    	
			    	if(i<30) {
			    		i++;
			    	Log.v("Output",m.group(1)+m.group(2)+m.group(3));
			    	}
			    	popularList.put(m.group(2),m.group(1));
			    }
			    
			}
			
			if(popularList.size()>0) {
				Log.v("OneManga", "Found " + String.valueOf(popularList.size()) + " number of manga.");
				return true;
			}
			else {
				Log.v("Error:", "Didn't find any animes.");
				return false;
			}
		}
		else {
			Log.e("Error:", http.returnError().toString(), http.returnError());
			return false;
		}
	}
	
	/*	bool	refreshRecentList
	 * 
	 */
	public static boolean refreshRecentList() {
		String temp = null;
		recentList = new LinkedHashMap();
		
		if(http.getPage(recent,url,true,true)) {
			temp = http.returnResult();
			
			if(temp == null) {
				Log.v("Output", "No Result returned. Exiting.");
				return false;
			}
			else { //Success, time to parse the list
				String regex = "<tr class=\".+\">[\\s]+<td class=\"ch-date-recent\">(.+)</td>[\\s]+<td><a href=\"(.+)\">(.+)</a></td>[\\s]+</tr>";
				
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(temp);
				
			    while(m.find()) {
			    	recentList.put(m.group(3),m.group(2));
			    }
			    
			}
			
			if(recentList.size()>0) {
				return true;
			}
			else {
				Log.v("Error:", "Didn't find any recent animes.");
				return false;
			}
		}
		else {
			Log.e("Error:", http.returnError().toString(), http.returnError());
			return false;
		}
	}
	
	/*	bool	refreshAnimeList
	 * 
	 */
	public static boolean refreshAnimeList() {
		String temp = null;
		animeList = new LinkedHashMap();
		
		if(http.getPage(list,url,false,false)) {
			temp = http.returnResult();
			
			if(temp == null) {
				Log.v("Output", "No Result returned. Exiting.");
				return false;
			}
			else { //Success, time to parse the list
				String regex = "\\[\"([^\"]+)\",\"([^\"]+)\"\\]";
				
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(temp);
				
				String l = null;
				String[] la = null;
				animeList = new TreeMap(); //Makes the map alphabetical
			    while(m.find()) {
			    	l = temp.substring(m.start(),m.end());
			    	
			    	l = l.substring(1,l.length()-1);
			    	
			    	if (l != null || !l.equalsIgnoreCase("")){
			            la = l.split("\\,");
			        }
			    	la[0] = la[0].substring(1,la[0].length()-1);
			    	la[1] = la[1].substring(1,la[1].length()-1);
			    	
			    	//Log.v(",",la[0]+"|"+la[1]);
			    	
			    	//Remove this entry from list
			    	if(!la[1].equals("random-manga")) {
			    		animeList.put(la[0],la[1]);
			    	}
			    }
			}
			
			if(animeList.size()>0) {
				return true;
			}
			else {
				Log.v("Error:", "Didn't find any animes.");
				return false;
			}
		}
		else {
			Log.e("Error:", http.returnError().toString(), http.returnError());
			return false;
		}
	}
	
	/*	bool	refreshChapterList
	 * 
	 */
	public static boolean refreshChapterList() {
		String temp = null;
		chaptersList = new LinkedHashMap(); 
		
		if(http.getPage(url + currentManga,url,true,true)) {
			temp = http.returnResult();
			
			if(temp == null) {
				Log.v("Output", "No Result returned. Exiting.");
				return false;
			}
			else { //Success, time to parse the list
				String regex = "<tr class=\".+\">[\\s]+<td class=\"ch-subject\"><a href=\"(.+)\">(.+)</a>(&nbsp;<img src=\"http://om-static.s-onemanga.com/manga/new.gif\"/>)?</td>[\\s]+<td class=\"ch-scans-by\">(.+)</td>[\\s]+<td class=\"ch-date\">(.+)</td>[\\s]+</tr>";
				
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(temp);
				
			    while(m.find()) {
			    	chaptersList.put(m.group(2),m.group(1));
			    	Log.v(",",m.group(2)+"|"+m.group(1));
			    }
			}
			
			if(chaptersList.size()>0) {
				return true;
			}
			else {
				Log.v("Error:", "Didn't find any chapters.");
				return false;
			}
		}
		else {
			Log.e("Error:", http.returnError().toString(), http.returnError());
			return false;
		}
	}
	
	/*	bool	evalImagePage()
	 * 
	 */
	public static boolean evalImagePage() {
		return false;
	}
	
	/*	bool	refreshPageList
	 *
	 * @desc	Purpose of this function is to figure out the first page of the chapter
	 * 			(not always 01) and than load that page while parsing it for the list
	 * 			of pages in the chapter.
	 * 
	 * @returns	True on success. False on failure.
	 */
	public static boolean refreshPageList() {
		String temp = null;
		String temp2 = null;
		String firstPage = null;
		
		pageList = new LinkedHashMap(); 
		
		String regex = null;
		String regex2 = null;
		
		if(http.getPage(url + currentChapter,url,true,true)) {
			temp = http.returnResult();
			
			if(temp == null) {
				Log.v("Output", "First page not found.");
				return false;
			}
			else { //Success, time to parse the list
				regex = "<li><a href=\"(.+)\">Begin reading .+</a>\\.</li>";
				
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(temp);
				
				
			    while(m.find()) {
			    	firstPage = m.group(1);
			    	
			    	if(http.getPage(url + firstPage,url,true,true)) {
						temp2 = http.returnResult();
						
						if(temp2 == null) {
							Log.v("Output", "No Result returned. Exiting.");
							return false;
						}
						else {
							// PULL OUT PAGE LIST
							regex2 = "<option value=\"([0-9_-]+)\".+>[0-9_-]+</option>";
							Pattern p2 = Pattern.compile(regex2);
							Matcher m2 = p2.matcher(temp2);
							
							while(m2.find()) {
								//Log.v("label",m2.group(1));
								pageList.put(m2.group(1), m2.group(1));
							}
							
							currentPage = null;
						}
			    	}
			    }
			}
			
			if(pageList.size()>0) {
				return true;
			}
			else {
				Log.v("Error:", "Didn't find the page list (" + url + currentChapter + ").");
				return false;
			}
		}
		else {
			Log.e("Error:", http.returnError().toString(), http.returnError());
			return false;
		}
	}
	
	public static boolean refreshNextPage() {
		String temp = currentPage;
		if(currentPage == null) {
			return refreshPageImageURL();
		}
		else {
			Iterator it = pageList.keySet().iterator();
			
	        int count = 0;
	        String next = null;
	        while (it.hasNext()) {
	        	
	        	next = it.next().toString();
	        	
	        	if(currentPage == next) {
	        		currentPage = it.next().toString();
	        		if(currentPage == null) {
	        			currentPage = temp;
	        			return false;
	        		}
	        		
	        		return refreshPageImageURL();
	        	}
	        }
		}
		return false;
	}
	
	public static boolean refreshPrevPage() {
		String temp = currentPage;
		if(currentPage == null) {
			return refreshPageImageURL();
		}
		else {
			Iterator it = pageList.keySet().iterator();
			
	        int count = 0;
	        String next = null;
	        String prev = null;
	        while (it.hasNext()) {
	        	prev = next;
	        	next = it.next().toString();
	        	
	        	if(currentPage == next) {
	        		currentPage = prev;
	        		if(currentPage == null) {
	        			currentPage = temp;
	        			return false;
	        		}
	        		return refreshPageImageURL();
	        	}
	        }
		}
		return false;
	}
	
	public static boolean refreshPageImageURL() {
		if(currentPage == null) {
			Iterator it = pageList.keySet().iterator();
	        int count = 0;
	        while (it.hasNext()) {
	        	currentPage = it.next().toString();
	        	break;
	        }
		}
		
		String temp = null;
		currentPageURL = null;
		
		if(http.getPage(url + currentChapter + currentPage + "/",url,true,true)) {
			temp = http.returnResult();
			
			if(temp == null) {
				Log.v("Output", "Page not found.");
				return false;
			}
			else { //Success, time to parse the list
				String regex = "<img class=\"manga-page\" src=\"(.+)\" alt=\".+\" />";
				
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(temp);
				
				
			    while(m.find()) {
			    	currentPageURL = m.group(1);
			    }
			}
			if(currentPageURL != null) {
				return true;
			}
			else {
				Log.v("Error:", "Didn't find the page image URL.");
				return false;
			}
		}
		else {
			Log.e("Error:", http.returnError().toString(), http.returnError());
			return false;
		}
	}
}
